//
//  Weather update server in C++
//  Binds PUB socket to tcp://*:5556
//  Publishes random weather updates
//
package main

import (
	"fmt"
	"os"
	"zmq"
	"rand"
	"time"
	"bytes"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	publisher, err := context.Socket(zmq.PUB)
	if err != nil {
		return err
	}
	defer publisher.Close()

	err = publisher.Bind("tcp://*:5556")
	if err != nil {
		return err
	}
	err = publisher.Bind("ipc://weather.ipc")
	if err != nil {
		fmt.Println("warning",err)
	}
	r := rand.New(rand.NewSource(time.Nanoseconds()))
	i := 0
	for {
		zipcode := r.Intn(20000)
		temperature := r.Intn(215) - 80
		relhumidity := r.Intn(50) + 10
		var buf bytes.Buffer
		fmt.Fprintf(&buf, "%05d %d %d", zipcode, temperature, relhumidity)
		publisher.Send(buf.Bytes(),0)
		i++
		if i >= 10000 {
			i = 0
			zmq.Sleep(1)
		}
	}
	return nil
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Weather update server!")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}